from flask import Flask, render_template, request, redirect, url_for, session
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['SECRET_KEY'] = 'your-secret-key'
db = SQLAlchemy(app)


# 定义用户模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))


# 初始化数据库（仅在生产环境中省略）
with app.app_context():
    db.create_all()

from werkzeug.security import generate_password_hash, check_password_hash


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        if user is None:
            # 如果用户不存在，则自动注册并登录
            new_user = User(username=username, password_hash=generate_password_hash(password))
            db.session.add(new_user)
            db.session.commit()
            session['user_id'] = new_user.id
            return redirect(url_for('home'))
        elif check_password_hash(user.password_hash, password):
            # 密码正确，登录用户
            session['user_id'] = user.id
            return redirect(url_for('home'))
        else:
            # 密码错误
            return 'Invalid username or password'
    return render_template('login.html')


@app.route('/logout')
def logout():
    session.pop('user_id', None)
    return redirect(url_for('login'))


@app.route('/')
def home():
    if 'user_id' in session:
        return 'Logged in as User ID: {}'.format(session['user_id'])
    else:
        return redirect(url_for('login'))